import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { SearchBar, Grid, Card } from 'antd-mobile';
import NoData from '../NoData';
import ProcessIcon from '../../web/components/ProcessIcon';
import { goto } from '../../commonUtils';
import { getApplyList, getApplyCategory } from './service';
import { getMessage } from '@inbiz/react';
import './index.less';

interface ApplyObj {
  ProLcon?: string;
  ProcessName: string;
  groupName: string;
  processDefinitionId: string;
}

const ProcessApply = forwardRef((props: any, ref) => {
  const { userInfo, rangeConfig, processGroup } = props;
  const [applyList, $applyList] = useState([]);
  const [applyCatogory, $applyCatogory] = useState<{ name: string; id: string }[]>([]);
  const [isSearch, $isSearch] = useState(false);
  const [nodata, $nodata] = useState(false);

  const searchApply = (value?: string) => {
    let params = {
      userId: userInfo.ID,
      pageIndex: 1,
      pageSize: 999,
      processName: value,
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    };
    getApplyList(params).then((res) => {
      if (res.details && res.details.rows) {
        $applyList(res.details.rows);
        $isSearch(Boolean(value));
        $nodata(false);
      } else {
        $applyList([]);
        $isSearch(Boolean(value));
        $nodata(true);
      }
    });
  };

  const getCategory = () => {
    let params = {
      userId: userInfo.ID,
      type: 'apply',
      groupType: 'Group',
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    };
    getApplyCategory(params).then((res) => {
      if (res.details.GroupData) {
        $applyCatogory(res.details.GroupData);
      }
    });
  };

  useImperativeHandle(ref, () => ({
    getCategory,
    searchApply,
  }));

  useEffect(() => {
    if (userInfo?.ID) {
      searchApply('');
      getCategory();
    }
    localStorage.setItem('inbiz-process-center-filterTab', '');
  }, [userInfo, rangeConfig]);

  return (
    <div className={'processApply'}>
      <SearchBar
        clearable
        onClear={searchApply}
        onSearch={searchApply}
        placeholder={getMessage('Processcenter.placeholder1H5')}
      />
      {isSearch && applyList.length > 0 && (
        <Card>
          <Grid columns={3}>
            {applyList.map((ele: ApplyObj, index) => {
              return (
                <Grid.Item
                  onClick={() =>
                    goto(
                      {
                        processDefinitionId: ele.processDefinitionId,
                        inItiateApplication: true,
                        siteType: 1,
                      },
                      '1',
                      'wap',
                    )
                  }
                  key={index}
                >
                  <div className={'applyBody'}>
                    <div className={'applyImage'}>
                      <ProcessIcon
                        processIconInfo={ele?.ProLcon ? ele?.ProLcon?.trim() : 'font_family'}
                        style={{ fontSize: 30 }}
                      />
                    </div>
                    <div className={'applyName'}>{ele.ProcessName}</div>
                  </div>
                </Grid.Item>
              );
            })}
          </Grid>
        </Card>
      )}
      {!isSearch &&
        applyCatogory.map((item: { name: string }, index: number) => {
          return (
            <Card title={item.name} key={index}>
              <Grid columns={3}>
                {applyList
                  .filter((element: ApplyObj) => element.groupName == item.name)
                  .map((ele: ApplyObj, eleIndex: number) => {
                    return (
                      <Grid.Item
                        onClick={() =>
                          goto(
                            {
                              processDefinitionId: ele.processDefinitionId,
                              siteType: 1,
                              inItiateApplication: true,
                            },
                            '1',
                            'wap',
                          )
                        }
                        key={eleIndex}
                      >
                        <div className={'applyBody'}>
                          <div className={'applyImage'}>
                            <ProcessIcon
                              processIconInfo={ele?.ProLcon ? ele?.ProLcon?.trim() : 'font_family'}
                              style={{ fontSize: 30 }}
                            />
                          </div>
                          <div className={'applyName'}>{ele.ProcessName}</div>
                        </div>
                      </Grid.Item>
                    );
                  })}
              </Grid>
            </Card>
          );
        })}
      <div style={{ height: 190 }}></div>
      {nodata && <NoData />}
    </div>
  );
});

export default ProcessApply;
